//
//  ScoreListViewController.m
//  Supermarket
//
//  Created by qskj-ios on 2018/12/11.
//  Copyright © 2018年 com.qiansheng. All rights reserved.
//

#import "ScoreListViewController.h"
#import "ScoreListCell.h"
#import "CGXPickerView.h"
#import "ScoreCommunityListCell.h"

@interface ScoreListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet UIButton *startButton;
@property (weak, nonatomic) IBOutlet UIButton *endButton;
@property (weak, nonatomic) IBOutlet UIButton *queryButton;
@property (assign, nonatomic) BOOL isQuery;
@property (strong, nonatomic) NSMutableArray *communityArray;

- (IBAction)didClickedStartButton:(id)sender;
- (IBAction)didClickedEndButton:(id)sender;
- (IBAction)didClickedQueryButton:(id)sender;

@end

@implementation ScoreListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.isQuery = NO;
    self.communityArray = [[NSMutableArray alloc] init];
    [self.startButton setTitle:@"请选择开始时间" forState:UIControlStateNormal];
    [self.endButton setTitle:@"请选择结束时间" forState:UIControlStateNormal];
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TopHeight+40, 0);
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ScoreListCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ScoreListCell class])];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ScoreCommunityListCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ScoreCommunityListCell class])];
    
    WEAKSELF
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf.dataArray removeAllObjects];
        [weakSelf.communityArray removeAllObjects];
        [weakSelf getDataSource];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(querySuccessNotification) name:@"QuerySuccessNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(querySingOutNotification) name:@"QuerySingOutNotification" object:nil];
}

- (void)querySuccessNotification {
    self.headView.hidden = YES;
    [self.tableView.mj_header beginRefreshing];
    self.isQuery = YES;
}

- (void)querySingOutNotification {
    self.headView.hidden = NO;
    [self.tableView.mj_header beginRefreshing];
    self.isQuery = NO;
}

- (void)getDataSource {
    WEAKSELF
    if (self.isQuery) {
        NSString *url = [NSString stringWithFormat:@"manager/getZxPoint?user_id=%@&mobile=%@", UserInfo.id, UserInfo.mobile];
        [NetworkHelper apiGet:url parameters:nil completion:^(id info, NSError *error) {
            [weakSelf.tableView.mj_header endRefreshing];
            if (!error) {
                if ([[info objectForKey:@"sta"] integerValue] == 1) {
                    [weakSelf.communityArray addObjectsFromArray:[ScoreModel mj_objectArrayWithKeyValuesArray:[info objectForKey:@"response"]]];
                }
                [SupermarketUtil setNullDataView:weakSelf.view withData:weakSelf.communityArray];
                [weakSelf.tableView reloadData];
            }
        }];
    } else {
        NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
        if (![self.startButton.titleLabel.text isEqualToString:@"请选择开始时间"]) {
            [parameters setObject:self.startButton.titleLabel.text forKey:@"start"];
        }
        if (![self.endButton.titleLabel.text isEqualToString:@"请选择结束时间"]) {
            [parameters setObject:self.endButton.titleLabel.text forKey:@"end"];
        }
        
        NSString *url = [NSString stringWithFormat:@"manager/point_log?do_id=%@", [SupermarketUtil getDataWithKey:@"do_id"]];
        [NetworkHelper apiPost:url parameters:parameters completion:^(id info, NSError *error) {
            [weakSelf.tableView.mj_header endRefreshing];
            if (!error) {
                if ([[info objectForKey:@"sta"] integerValue] == 1) {
                    NSDictionary *dict = [info objectForKey:@"response"];
                    [weakSelf.dataArray addObjectsFromArray:[ScoreModel mj_objectArrayWithKeyValuesArray:[dict objectForKey:@"list"]]];
                }
                [SupermarketUtil setNullDataView:weakSelf.view withData:weakSelf.dataArray];
                [weakSelf.tableView reloadData];
            }
        }];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isQuery) {
        return self.communityArray.count;
    } else {
        return self.dataArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isQuery) {
        ScoreCommunityListCell *scoreCell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ScoreCommunityListCell class]) forIndexPath:indexPath];
        scoreCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        ScoreModel *scoreModel = [self.communityArray objectAtIndex:indexPath.row];
        [scoreCell setContentWithScore:scoreModel];
        
        //存储每个社区扣除的积分
        WEAKSELF
        scoreCell.scoreEditingDelegate = ^(UITableViewCell * _Nonnull cell, NSInteger reduceScore) {
            NSIndexPath *indexpath = [tableView indexPathForCell:cell];
            ScoreModel *scoreModel = [weakSelf.communityArray objectAtIndex:indexpath.row];
            scoreModel.reduceScore = reduceScore;
        };
        
        return scoreCell;
        
    } else {
        ScoreListCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ScoreListCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        ScoreModel *model = [self.dataArray objectAtIndex:indexPath.row];
        [cell setContentWithScore:model];
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isQuery) {
        return 87;
    } else {
        return 50;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (self.isQuery) {
        return 100;
    } else {
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 100)];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(kScreenWidth/2-100, 30, 200, 40);
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button setTitle:@"确定" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setBackgroundColor:RGB_COLOR(30, 194, 137)];
    button.clipsToBounds = YES;
    button.cornerRadius = 5;
    [button addTarget:self action:@selector(didClickedSureButton) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    return view;
}

//扣除积分
- (void)didClickedSureButton {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    
    //社区中心、id
    NSMutableArray *zxIDArray = [[NSMutableArray alloc] init];
    
    //总积分
    NSInteger score = 0;
    for (ScoreModel *model in self.communityArray) {
        score = score + model.reduceScore;
        
        if (model.point < model.reduceScore) {
            [SVProgressHUD showErrorWithStatus:@"您的积分不够！"];
            return;
        }
        
        NSString *zxID = [NSString stringWithFormat:@"%@|%ld", model.zx_id, (long)model.reduceScore];
        [zxIDArray addObject:zxID];
    }
    
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    [parameters setObject:UserInfo.id forKey:@"id"];
    [parameters setObject:UserInfo.mobile forKey:@"mobile"];
//    [parameters setObject:[SupermarketUtil getDataWithKey:@"do_id"] forKey:@"do_id"];
    [parameters setObject:@(score) forKey:@"point"];
    [parameters setObject:[zxIDArray componentsJoinedByString:@","] forKey:@"zx_id"];
    
    [SVProgressHUD showWithStatus:@"积分扣除中..."];
    WEAKSELF
    [NetworkHelper apiPost:@"manager/deDuction" parameters:parameters completion:^(id info, NSError *error) {
        [SVProgressHUD dismiss];
        if (!error) {
            NSString *remarks = [info objectForKey:@"remarks"];

            if ([[info objectForKey:@"sta"] integerValue] == 1) {
                [weakSelf.tableView.mj_header beginRefreshing];
                [SVProgressHUD showSuccessWithStatus:remarks];
            } else {
                [SVProgressHUD showErrorWithStatus:remarks];
            }
        }
    }];
}

//查询开始时间
- (IBAction)didClickedStartButton:(id)sender {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *nowStr = [fmt stringFromDate:now];
    
    WEAKSELF
    [CGXPickerView showDatePickerWithTitle:@"" DateType:UIDatePickerModeDateAndTime DefaultSelValue:nil MinDateStr:@"2010-01-01 00:00:00" MaxDateStr:nowStr IsAutoSelect:YES Manager:nil ResultBlock:^(NSString *selectValue) {
        [weakSelf.startButton setTitle:selectValue forState:UIControlStateNormal];
        [weakSelf.startButton setTitleColor:kTextColorOne forState:UIControlStateNormal];
    }];
}

//查询结束时间
- (IBAction)didClickedEndButton:(id)sender {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    NSDate *now = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *nowStr = [fmt stringFromDate:now];
    
    WEAKSELF
    [CGXPickerView showDatePickerWithTitle:@"" DateType:UIDatePickerModeDateAndTime DefaultSelValue:nil MinDateStr:@"2010-01-01 00:00:00" MaxDateStr:nowStr IsAutoSelect:YES Manager:nil ResultBlock:^(NSString *selectValue) {
        [weakSelf.endButton setTitle:selectValue forState:UIControlStateNormal];
        [weakSelf.endButton setTitleColor:kTextColorOne forState:UIControlStateNormal];
    }];
}

//查询
- (IBAction)didClickedQueryButton:(id)sender {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
    if ([self.startButton.titleLabel.text isEqualToString:@"请选择开始时间"]) {
        [SVProgressHUD showErrorWithStatus:@"请选择开始时间"];
        return;
    }
    if ([self.endButton.titleLabel.text isEqualToString:@"请选择结束时间"]) {
        [SVProgressHUD showErrorWithStatus:@"请选择结束时间"];
        return;
    }
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
